package com.chufuying.tools.services.impl;
import com.chufuying.tools.beans.ColumnInfoForTable;
import com.chufuying.tools.services.FindTables;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取数据库中所有的表
 * @autor:Faizel
 * @date:2017-03-04
 * @version:1.0.0
 * */

public class FindTablesImpl implements FindTables {
    /**
     * 获得可中所有表
     *
     * @param con*
     */
    @Override
    public Map<String, List<ColumnInfoForTable>> Find(Connection con) {
        Map<String, List<ColumnInfoForTable>> map = new HashMap<>();
        linkDB(map, con);
        return map;
    }

    /**
     * 连接数据库，读取表信息
     *
     * @param map
     * @param con*
     */
    @Override
    public void linkDB(Map<String,List<ColumnInfoForTable>> map, Connection con) {
        List<ColumnInfoForTable> list = new ArrayList<>();
        ResultSet rs;
        try {
            DatabaseMetaData dbm = con.getMetaData();
            rs = dbm.getTables(null, null, null, null);
            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
                ResultSet res = dbm.getColumns(null,null,tableName, null);
                while(res.next()){
                    ColumnInfoForTable ci = new ColumnInfoForTable();
                    ci.setColumnName(res.getString("COLUMN_NAME"));
                    ci.setColumnTypeCode(res.getInt("DATA_TYPE"));
                    list.add(ci);
                }
                String first = tableName.charAt(0) + "";
                map.put(tableName.replaceFirst(first, first.toUpperCase()),list);
                res.close();
            }
            rs.close();
        }
        catch (Exception e){

            e.printStackTrace();

        }
    }
}
